<template>
    <div id="root">
        <div class="todo-container">
            <div class="todo-wrap">
                <TodoHeader @accept="accept"></TodoHeader>
                <TodoList :todos="todos"></TodoList>
                <TodoFooter :todos="todos" @clearDone="clearDone"></TodoFooter>
            </div>
        </div>
    </div>
</template>

<script>
    import TodoFooter from './components/TodoFooter.vue'
    import TodoHeader from './components/TodoHeader.vue'
    import TodoList from './components/TodoList.vue'
    export default {
        name: 'App',
        components: {
            TodoFooter,
            TodoHeader,
            TodoList
        },
        data() {
          return {
            //   todos2:[// 放在这里, 不方便兄弟组件之间的通信, 所以考虑放在父组件中
            //       {id:1, title:'吃饭', completed:true},
            //       {id:2, title:'睡觉', completed:false},
            //       {id:3, title:'打豆豆', completed:true}
            //   ]
            todos: JSON.parse(window.localStorage.getItem('todos') || '[]')
          }
      },
      methods: {
        accept(e) { //传递给子组件的方法
            this.todos.unshift(e)
        },
        handleCheck(id) {
            console.log('@@@@'+id)
            this.todos.forEach(item => {
                if(item.id === id) {
                    item.completed = !item.completed // 取反
                }
            })
        },
        handleDelete(id) {
            console.log('@@@@'+id)
            this.todos = this.todos.filter(item => item.id !== id)
        },
        clearDone() {
            this.todos = this.todos.filter(item => !item.completed)
        }
      },
      watch:{
        todos: {
            handler(value) {
                window.localStorage.setItem('todos', JSON.stringify(value))
            },
            deep: true // 深度监视, 可以监视到数组中对象的变化
        }
      },
      mounted() {
        this.$bus.$on('handleCheck', this.handleCheck)
        this.$bus.$on('handleDelete', this.handleDelete)
      },
      beforeDestroy() {
        this.$bus.$off('handleCheck')
        this.$bus.$off('handleDelete')
      }
    }
</script>

<!-- 全局样式 -->
<style>
    /*base*/
    body {
    background: #fff;
    }

    .btn {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    }

    .btn-danger {
    color: #fff;
    background-color: #da4f49;
    border: 1px solid #bd362f;
    }

    .btn-danger:hover {
    color: #fff;
    background-color: #bd362f;
    }

    .btn:focus {
    outline: none;
    }


    /*app*/
    .todo-container {
    width: 600px;
    margin: 0 auto;
    }
    .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    }



    
    

    

</style>